#include "database.h"

DataBase::DataBase()
{
    dataBase = QSqlDatabase::addDatabase("QSQLITE");
    dataBase.setDatabaseName("MyDataBase.db");
    OpenDb();
    CreateTable();
    qDebug()<<IsTableExist("student");\
    InsertData("");
}

void DataBase::OpenDb()
{
    if (!dataBase.open())
    {
        qDebug() << "Error: Failed to connect database." << dataBase.lastError();
    }
    else
    {
        qDebug()<<"success";
    }


}

void DataBase::CreateTable()
{
    // 用于执行sql语句的对象
    QSqlQuery sqlQuery;
    // 构建创建数据库的sql语句字符串
    QString createSql = QString("CREATE TABLE student (\
                                id INT PRIMARY KEY NOT NULL,\
                                name TEXT NOT NULL,\
                                age INT NOT NULL)");
            sqlQuery.prepare(createSql);
    // 执行sql语句
    if(!sqlQuery.exec())
    {
        qDebug() << "Error: Fail to create table. " << sqlQuery.lastError();
    }
    else
    {
        qDebug() << "Table created!";
    }
}

bool DataBase::IsTableExist(QString tableName)
{
    QSqlDatabase database = QSqlDatabase::database();
    if(database.tables().contains(tableName))
    {
        return true;
    }

    return false;
}

bool DataBase::InsertData(QString name)
{
    QSqlQuery sqlQuery;
    sqlQuery.prepare("INSERT INTO student VALUES(:id,:name,:age)");
    sqlQuery.bindValue(":id",15);
    sqlQuery.bindValue(":name","我好");
    sqlQuery.bindValue(":age", 12);
    if(!sqlQuery.exec())
    {
        qDebug() << "Error: Fail to insert data. " << sqlQuery.lastError();
    }
    else
    {
        return  true;
    }
}
